//
//  UIWebView+Extension.swift
//  UICPortal
//
//  Created by 高宇超 on 7/17/17.
//  Copyright © 2017 Yuchao. All rights reserved.
//

import UIKit

// MARK :- WebView, grab information from html
extension UIWebView {
    
    func loadHTML(html: String) {
        guard let url = URL(string: html.percentEncoding()) else { return }
        let request = URLRequest(url: url)
        self.loadRequest(request)
    }
    
    func doLogin(username: String, pwd: String) {
        stringByEvaluatingJavaScript(from: "var script = document.createElement('script');script.type = 'text/javascript';script.text = function ycDoLogin() { var username = document.getElementById('username'); var pwd = document.getElementsByName('password')[0]; username.value = '\(username)@student'; pwd.value = '\(pwd)'; var form = document.getElementsByName('login_form')[0]; form.submit(); };document.getElementsByTagName('head')[0].appendChild(script);")
        stringByEvaluatingJavaScript(from: "ycDoLogin();")
    }
    
    func doLogout() {
        stringByEvaluatingJavaScript(from: "logout();")
    }
    
    func goToMIS() {
        stringByEvaluatingJavaScript(from: "login(mis);")
    }
    
    func goToiSpace() {
        stringByEvaluatingJavaScript(from: "login(iSpace);")
    }
    
    func rtrvProfile(byClassName className: String) -> String {
        stringByEvaluatingJavaScript(from: "var script = document.createElement('script');script.type = 'text/javascript';script.text = function rtrvProfile() { var profile = document.getElementsByClassName('\(className)')[0]; var item = profile.getElementsByTagName('span')[0]; return item.innerText; }; document.getElementsByTagName('head')[0].appendChild(script);")
        guard let name = self.stringByEvaluatingJavaScript(from: "rtrvProfile();") else { return "" }
        return name
    }
    
    func rtrvGender() -> String {
        stringByEvaluatingJavaScript(from: "var script = document.createElement('script');script.type = 'text/javascript';script.text = function rtrvGender() { var table = document.getElementsByClassName('border1')[0]; var td = table.getElementsByTagName('tr')[1].getElementsByTagName('td')[3]; return td.innerText; }; document.getElementsByTagName('head')[0].appendChild(script);")
        guard let gender = self.stringByEvaluatingJavaScript(from: "rtrvGender();") else { return "" }
        return gender == "M" ? "Male" : "Female"
    }
    
    func rtrvOtherProfile(index: Int) -> String {
        stringByEvaluatingJavaScript(from: "var script = document.createElement('script');script.type = 'text/javascript';script.text = function rtrvOtherProfile() { var profile = document.getElementsByClassName('other')[\(index)]; var item = profile.getElementsByTagName('span')[0]; return item.innerText; }; document.getElementsByTagName('head')[0].appendChild(script);")
        guard let other = self.stringByEvaluatingJavaScript(from: "rtrvOtherProfile();") else { return "" }
        return other
    }
    
    
    func rtrvTimetableAndSave(_ user: UserRealm) -> [Int: [Int: ClassRealm]] {
        stringByEvaluatingJavaScript(from: "var script = document.createElement('script');script.type = 'text/javascript';script.text = function rtrvTimetable() { var timetable = document.getElementById('mytimetable'); var trs = timetable.getElementsByTagName('tr'); var str = new Array(); str[0] = ''; str[1] = ''; str[2] = ''; str[3] = ''; str[4] = ''; str[5] = ''; for (var i = 0; i < trs.length; i++) { if (i > 0) { var tr = trs[i]; var tds = tr.getElementsByTagName('td'); for (var j = 0; j < tds.length; j++) { var tt = '[' + (i + 7) + ']'; var td = tds[j]; str[j] += (tt + td.innerText); }}} return str[0] + '[]' + str[1] + '[]' + str[2] + '[]' + str[3] + '[]' + str[4] + '[]' + str[5]; }; document.getElementsByTagName('head')[0].appendChild(script);")
        guard let timetableString = self.stringByEvaluatingJavaScript(from: "rtrvTimetable();") else { return [:] }
        parseTimetableString(timetableString, user: user)
        return [Int: [Int: ClassRealm]]()
    }
    
    func parseTimetableString(_ timetableString: String, user: UserRealm) {
        RealmHelper.removeAllClass()
        let table = timetableString.components(separatedBy: "[]")
        let teacherDict = self.retrieveTimetableTeachers()
        printit(teacherDict)
        for (i, course) in table.enumerated() {
            let weekday = weekdays[i]!
            var lastClass = ClassOneRealm()
            for t in 8..<22 {
                var one = course.components(separatedBy: "[\(t)]")
                if one.count < 2 { break }
                one = one[1].components(separatedBy: "[\(t + 1)]")
                if one[0].count > 1 {
                    var title = ""
                    var classroom = ""
                    //print("--------------------------------")
                    // class date and time
                    print("\(weekday) \(t)-\(t + 1)")
                    for (i, o) in one[0].components(separatedBy: CharacterSet.newlines).enumerated() {
                        if i == 0 {
                            // class title name
                            title = o
                            //print("title \(o)")
                        } else if i == 1 && o.count > 2 {
                            // classroom
                            classroom = o
                            //print("classroom \(o)")
                        }
                    }
                    var minutes = 60
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = "hh:mm:ss"
                    let startDate = dateFormatter.date(from: "\(t):00:00")

                    var classOneRealm = ClassOneRealm()
                    var shouldAdd = true
                    if let courseTitle = lastClass.course?.title, let courseWeekday = lastClass.weekday {
                        if courseTitle == title && courseWeekday == weekday {
                            shouldAdd = false
                            classOneRealm = lastClass
                            minutes += lastClass.minutes
                            RealmHelper.setClassOne(classOneRealm: classOneRealm, minutes: minutes, endTime: t + 1)
                        }
                    }

                    if shouldAdd {
                        classOneRealm.user = user.username
                        classOneRealm.weekday = weekday
                        classOneRealm.startDate = startDate
                        classOneRealm.minutes = minutes
                        classOneRealm.startTime = t
                        classOneRealm.endTime = t + 1
                        classOneRealm.classroom = classroom
                        RealmHelper.addClassOne(classOneRealm)
                    }
                
                    if let classRealm = RealmHelper.retrieveClass(by: title, user: user.username) {
                        RealmHelper.setClassOneCourse(classOneRealm, course: classRealm)
                    } else {
                        let classRealm = ClassRealm()
                        classRealm.user = user.username
                        classRealm.title = title
                        classRealm.teacher = teacherDict[title]
                        RealmHelper.addClass(classRealm)
                        RealmHelper.setClassOneCourse(classOneRealm, course: classRealm)
                    }
                    //print("--------------------------------")
                    lastClass = classOneRealm
                }
            }

            // classes after 22:00
            let one = course.components(separatedBy: "[22]")
            if one.count < 2 { break }
            if one[1].count > 1 {
                //print("--------------------------------")
                //print("\(weekdays[i]!)\t\(22)-\(23)")
                for (i, o) in one[1].components(separatedBy: CharacterSet.newlines).enumerated() {
                    if i == 0 {
                        //print(o)
                    }
                    if i == 1 && o.count > 2 {
                        //print(o)
                    }
                }
                //print("--------------------------------")
            }
        }
    }
    
    
    func retrieveTimetableTeachers() -> [String: String] {
        stringByEvaluatingJavaScript(from: "var script = document.createElement('script');script.type = 'text/javascript';script.text = function rtrvTimetableTc() { var table = document.getElementsByClassName('tablestyle-2')[0].getElementsByTagName('tbody')[0]; var trs = table.getElementsByTagName('tr'); var str = ''; for (var i = 0; i < trs.length; i++) { if (i > 0) { var tr = trs[i]; var tds = tr.getElementsByTagName('td'); if (tds.length > 3) {str += tds[0].innerText +  '||' + tds[1].innerText + '[]'; }}} return str; }; document.getElementsByTagName('head')[0].appendChild(script);")
        guard let teachers = self.stringByEvaluatingJavaScript(from: "rtrvTimetableTc();") else { return [:] }

        var dict = [String: String]()
        for teacher in teachers.components(separatedBy: "[]") {
            let courseAndTeacher = teacher.components(separatedBy: "||")
            if courseAndTeacher.count == 2 {
                let courseName = courseAndTeacher[0]
                let teacher = courseAndTeacher[1]
                dict[courseName] = teacher
            }
        }
        return dict
    }
    
}


